<template>
  <div id="printBarcodeMZ">
    <Breadcrumb content="门诊条码打印" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="16">
          <vxe-form :data="newForm" class-name="padding-sm width-100-percentage" title-width="80px">

            <vxe-form-item title="扫码" :item-render="{}" field="ewmNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.ewmNo" ref="ewmNoInput" placeholder="二维码" class-name="width-100-percentage"
                  @keyup="EWMNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>
            <vxe-form-item title="病历号" field="patNo" class-name="width-100-percentage" :item-render="{}">
              <template #default="{ data }">
                <vxe-input v-model="data.patNo" ref='patNoInput' placeholder="病历号" class-name="width-100-percentage"
                  :disabled="loading" clearable @keyup="EWMNoValueChangeEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病历号前缀" :item-render="{}" field="beforePatNo" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.beforePatNo" placeholder="病历号前缀" class-name="width-100-percentage"
                  :disabled="loading" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请号" :item-render="{}" field="reqNo" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.reqNo" placeholder="申请号" class-name="width-100-percentage" :disabled="loading"
                  clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>
            <!--2024-12-16应要求门诊条码不显示床号-->
            <!--            <vxe-form-item title="床号" :item-render="{}" field="bedNo" class-name="width-100-percentage no-edit">-->
            <!--              <template #default="{ data }">-->
            <!--                <vxe-input v-model="data.bedNo" placeholder="床号" class-name="width-100-percentage" clearable @keyup="keyupEnter" />-->
            <!--              </template>-->
            <!--            </vxe-form-item>-->

            <!--            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage no-edit">-->
            <!--              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[-->
            <!--                { title: '编码', props: 'code' }, //列标题-->
            <!--                { title: '名称', props: 'name' }-->
            <!--              ]" :title="'点击选择病人来源'" :searchParam="{ code: 'PATTYPE' }" @selectDataRow="SelectRowClick" :inputWidth="'180px'" v-model="newForm.patTypeName" :placeholder="'选择病人来源'" @clearValue="clearPatTypeName" />-->
            <!--            </vxe-form-item>-->
            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage no-edit">
              <SelectDataCheckedList ref="patTypeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :column="[
                { field: 'code', title: '编码' }, //列标题
                { field: 'name', title: '名称' }
              ]" :searchParam="{ code: 'PATTYPE' }" :isPage="false" @SelectCellClick="(e) => {
  selectPatTypeNameRow(e, rowIndex);
}" :clickRowId="typeIds" :showField="'name'" :inputWidth="'100%'">
              </SelectDataCheckedList>
            </vxe-form-item>

            <vxe-form-item title="科室" :item-render="{}" field="deptNa" class-name="width-100-percentage no-edit">
              <!-- <template #default="{ row }">
                                <span>{{ formatItemNameByIds(row) }}</span>
                            </template> -->
              <!-- <template #edit="{ rowIndex }"> -->
              <SelectDataCheckedList :url="'/api/sys/getDepartmentList'" :column="[
                { field: 'code', title: '科室编码' }, //列标题
                { field: 'name', title: '科室名称' }
              ]" :searchParam="{ orgId }" :isPage="false" @SelectCellClick="(e) => {
  selectRow(e, rowIndex);
}
  " :clickRowId="deptIds" :showField="'name'">
              </SelectDataCheckedList>
              <!-- </template> -->
              <!-- <template #default="{ data }">
                                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" clearable
                                    @keyup="keyupEnter" />
                            </template> -->
            </vxe-form-item>

            <vxe-form-item title="姓名" :item-render="{}" field="patNa" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" :disabled="loading"
                  clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="身份证号" :item-render="{}" field="IDNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input ref="refInputIDNo" v-model="data.IDNo" placeholder="身份证号" class-name="width-100-percentage"
                  @keyup="IDNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[始]" :item-render="{}" field="reqDateS" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[始]" v-model="data.reqDateS" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[止]" :item-render="{}" field="reqDateE" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[止]" v-model="data.reqDateE" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>
          </vxe-form>
        </Pane>
        <Pane size="64">
          <Splitpanes horizontal>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <!--                    <vxe-input v-model="newForm.searchValue1" placeholder="请输入关键字" clearable @clear="findPrintBarcodeSpecList()" @keyup="keyupEnter"></vxe-input>-->
                    <vxe-button type="text" icon="vxe-icon-search" class="button-blue margin-left-sm"
                      class-name="text-blue" :disabled="loading" content="查询"
                      @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-paste"
                      class-name="text-green" content="读卡" @click="IdNoFocus"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-print" class="button-blue margin-left-sm"
                      class-name="text-orange" content="打印" :loading="isPrintting" :disabled="isPrintting"
                      @click="printManyStep1('printBarcodeMZTable')"></vxe-button>
                    <!-- <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange" content="测试插入申请项目" @click="testInsertAppItem"></vxe-button> -->
                    <!-- <vxe-button type="text" icon="vxe-icon-maximize" class-name="text-olive" content="重新打印" @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete-fill" class-name="text-red" content="删除" @click="findPrintBarcodeSpecList"></vxe-button> -->
                    <vxe-checkbox v-model="isPrintZYD" class="margin-left-xs">打印回执单</vxe-checkbox>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom"
                      @dblclick="setCurComputerCheckedisPrintZYD">待打印条码申请</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeMZTable"
                :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px)' }">
                <vxe-table ref="printBarcodeMZTable" v-loading="loading" class="mytable-scrollbar" border height="auto"
                  align="left" :menu-config="tableMenuTop" :cell-style="cellStyle" :cell-class-name="cellClassName"
                  @checkbox-change="checkboxStateChange" @cell-click="printBarcodeMZRowClick"
                  :row-config="{ isCurrent: true, isHover: true }"
                  :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }" resizable show-overflow
                  :scroll-y="{ enabled: true, gt: 50 }" show-footer :footer-method="footerMethodTop"
                  :sort-config="{ defaultSort: { field: 'reqNo', order: 'asc' } }" :data="printBarcodeList"
                  :merge-footer-items="[{ row: 0, col: 1, rowspan: 1, colspan: 23 }]" :checkbox-config="checkboxConfig"
                  :tooltip-config="tooltipConfig">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"
                        v-if="!IsEmpty(row.catchMessage)"></span>
                      <span class="margin-left-xs" v-if="!IsEmpty(row.catchMessage)">{{ !IsEmpty(row.catchMessage) ?
                        row.catchMessage : '' }}</span>

                      <!--                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>-->
                      <!--                      <span class="margin-left-xs" v-if="row.isCatch">{{-->
                      <!--                        row.isCatch ? row.catchMessage : ''-->
                      <!--                      }}</span>-->
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" width="26" align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" sortable :sort-type="'string'" width="95px"></vxe-column>
                  <vxe-column field="patTypeNa" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px"></vxe-column>
                  <vxe-column field="sexNa" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDeptNa" title="科室" width="80px"></vxe-column>
                  <vxe-column field="sampleTypeNa" title="样本类型" width="100"></vxe-column>
                  <vxe-column field="feeName" title="申请项目名称" width="280"></vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctorNa" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60"></vxe-column>
                  <vxe-column field="price" title="金额" width="60"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input v-model="newForm.searchValue2" placeholder="请输入关键字" clearable
                      @clear="newForm.searchValue2 = ''" @keyup="selectAllAfterPrintSpecs"></vxe-input>
                    <vxe-button type="text" icon="vxe-icon-print" class="button-blue margin-left-sm"
                      class-name="text-green" content="重新打印" @click="printAgain"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete" class="button-blue margin-left-sm"
                      class-name="text-red" content="清空已打印" @click="deleteAllAfterPrintSpecs"></vxe-button>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">已打印条码</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeMZTable" :style="{
                height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px - 8px)'
              }">
                <vxe-table ref="afterPrintBarcodeSpecTable" v-loading="afterloading" @menu-click="contextMenuClickEvent"
                  class="mytable-scrollbar" border height="auto" align="center" :menu-config="tableMenuBottom"
                  :cell-style="cellStyle" :cell-class-name="cellClassName" :data="selectAfterPrintBarcodeSpecList"
                  @checkbox-change="afterCheckboxStateChange" :row-config="{ isCurrent: true, isHover: true }"
                  :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }"
                  resizable show-overflow :scroll-y="{ enabled: true, gt: 50 }" :checkbox-config="checkboxConfig"
                  :tooltip-config="tooltipConfig" :sort-config="{ defaultSort: { field: 'fixedSeq', order: 'desc' } }">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column field="fixedSeq" title="#" width="30" sortable></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"
                        v-if="!IsEmpty(row.catchMessage)"></span>
                      <span class="margin-left-xs" v-if="!IsEmpty(row.catchMessage)">{{ !IsEmpty(row.catchMessage) ?
                        row.catchMessage : '' }}</span>
                      <!--                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>-->
                      <!--                      <span class="margin-left-xs" v-if="row.isCatch">{{-->
                      <!--                        row.isCatch ? row.catchMessage : ''-->
                      <!--                      }}</span>-->
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" width="26" align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" sortable :sort-type="'string'" align="left"
                    width="95px"></vxe-column>
                  <vxe-column field="patTypeNa" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px" align="left"></vxe-column>
                  <vxe-column field="sexNa" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDeptNa" title="科室" width="80px" align="left"></vxe-column>
                  <vxe-column field="sampleTypeNa" title="样本类型" width="100" align="left"></vxe-column>
                  <vxe-column field="feeName" title="申请项目名称" width="280" align="left"></vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctorNa" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100" align="left"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px" align="left"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
        <Pane size="20">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="newForm.searchValue3" placeholder="请输入关键字" clearable @clear="findPatientList"
                @keyup.enter.native="findPatientList"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue margin-left-sm" class-name="text-orange"
                content="刷新" @click="RefreshPatientList"></vxe-button>
              <!--<vxe-checkbox v-model="isPrintZYD" class="margin-left-xs">打印指引单</vxe-checkbox> -->
            </template>
          </vxe-toolbar>
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" class-name="text-white text-bold bg-blue" class="button-blue margin-left-sm"
                content="一天" @click="changeDateCondition(1)"></vxe-button>
              <vxe-button type="text" class-name="text-white text-bold margin-left-xs bg-blue"
                class="button-blue margin-left-sm" content="三天" @click="changeDateCondition(3)"></vxe-button>
              <vxe-button type="text" class-name="text-white text-bold margin-left-xs bg-blue"
                class="button-blue margin-left-sm" content="五天" @click="changeDateCondition(5)"></vxe-button>
              <vxe-button type="text" class-name="text-white text-bold margin-left-xs bg-blue"
                class="button-blue margin-left-sm" content="七天" @click="changeDateCondition(7)"></vxe-button>
              <vxe-button type="text" class-name="text-white text-bold margin-left-xs bg-blue"
                class="button-blue margin-left-sm" content="一月" @click="changeDateCondition(30)"></vxe-button>
              <vxe-button type="text" class-name="text-white text-bold margin-left-xs bg-blue"
                class="button-blue margin-left-sm" content="三月" @click="changeDateCondition(90)"></vxe-button>
            </template>
          </vxe-toolbar>
          <div style="height: calc(100% - 60px)">
            <vxe-table :align="'left'"
              :data="patList.filter((data) => !newForm.searchValue3 || (newForm.searchValue3 && ((data.patNo && data.patNo.includes(newForm.searchValue3)) || (data.patNa && data.patNa.includes(newForm.searchValue3)) || (data.idNo && data.idNo.includes(newForm.searchValue3)))))"
              class="mytable-scrollbar" show-overflow border v-loading="loadingPat" :scroll-y="{ enabled: true }"
              height="auto" :checkbox-config="{ trigger: 'row', highlight: true, range: true }"
              :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true }"
              @cell-dblclick="dblclickRowSelect" :column-config="{ resizable: true }">
              <vxe-column type="seq" width="30"></vxe-column>
              <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
              <vxe-column field="patNa" title="姓名" width="80px"></vxe-column>
              <vxe-column field="sex" title="性别" width="30px"></vxe-column>
              <vxe-column field="ageStr" title="年龄" width="60px"></vxe-column>
              <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
              <vxe-column field="patId" title="病人编号" width="100px"></vxe-column>
              <vxe-column field="birthDay" title="出生日期" width="100px"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 静默打印-指引单 -->
    <QuietPrint ref="quietPrintZydRef" :printParams="printParamsZydObj" />
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, formatDateTime, splitArray } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance, List } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes'; //比例拖拉条
import SelectDataList from '@/components/SelectDataList.vue';
import { AppStore } from '../../../stores/store';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import QuietPrint from '@/components/QuietPrint.vue';
import { initWebSocket, closeWebSocket } from '@/utils/websocketReadCard';
import { getOptionValueByCodeGlobalOption, getOptionValueByCodeRptGroupOption } from '@/utils/SysOptionsHelper';
import { GetGolbalOptions } from '@/utils/SysOptionsHelper';
import { LocGet, LocPost } from '@/utils/LocRequestHelper';
import XEClipboard from 'xe-clipboard';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 双击配置本机电脑默认病人来源1
let isPrintting = ref(false);
let showDefaultVisitTypeModal = false;
let isPrintZYD = ref(false); //是否打印指引单
let isChildren = false;
let loading = ref(false);
let loadingPat = ref(false);
let patNoInput = ref(null);
let afterloading = ref(false);
let afterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let selectAfterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let printBarcodeList: any = reactive([]); //待打印列表
let patList: any = reactive([]); //右侧病人信息列表
let feeCodes: any = reactive([]); //右侧病人信息列表
let isAutoPrint = ref('0');/**系统选项参数扫码后是否自动打印 */
let currentPrintBarcode = reactive({}) as any; //当前选中行
let currentRowIndex = ref(0);
let printParamsObj = ref(null);//打印参数
let printParamsZydObj = ref(null); /**指引单打印参数 */
let deptIds = ref('');
let typeIds = ref('1');
let reportId = ref('');
let barCadeIds = ref('');
let orgId = ref(null);
let afterPrintBarcodeSpecTable = ref(null);/* 已打印表格对象 */
const patTypeSelectRef = ref(null);/**来源下拉框 */
const printBarcodeMZTable = ref(null); //表格ref标记

const newForm = reactive({
  searchValue1: '',
  searchValue2: '',
  searchValue3: '',
  patNo: '',
  beforePatNo: '',
  reqNo: '',
  bedNo: '',
  patType: [1, 2] as any,
  patTypeName: '门诊,急诊',
  deptNo: [] as any,
  deptNa: '',
  patNa: '',
  IDNo: '',
  ewmNo: '', //二维码
  reqDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  reqDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59'),
  filterotherDept: 0
});

let tableMenuTop = reactive({
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
        {
          code: 'print',
          name: '打印选中',
          prefixIcon: 'vxe-icon-print',
          className: 'my-copy-item'
        },
        {
          code: 'refresh',
          name: '刷新列表',
          prefixIcon: 'vxe-icon-refresh',
          className: 'my-copy-item'
        }
      ]
    ]
  }
});
let tableMenuBottom = reactive({
  className: 'my-menus',
  body: {
    options: [
      [
        { code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }
      ]
    ]
  }
});
const checkboxConfig = reactive<VxeTablePropTypes.CheckboxConfig<RowVO>>({
  checkMethod: ({ row }) => {
    return IsEmpty(row.catchMessage)
  }
});
const formData = reactive({})
const tooltipConfig = reactive<VxeTablePropTypes.TooltipConfig>({
  showAll: true,
  enterable: true,
  contentMethod: ({ type, column, row, items, _columnIndex }) => {
    const { field } = column;
    // 重写默认的提示内容
    if (field === 'feeName') {
      return formData[row.feeCode];
    }
  }
});
// 页面加载时更新报告单元/字典
onMounted(async () => {

  let aaa = getOptionValueByCodeGlobalOption('mztmdymrcxts') ? getOptionValueByCodeGlobalOption('mztmdymrcxts') : 0;
  newForm.reqDateS = formatDateTime(new Date().valueOf() - Number(aaa) * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');

  try {
    GetGolbalOptions();
  } catch (error) {
    console.log(error);
  }
  isAutoPrint.value = getOptionValueByCodeGlobalOption('mztmdysmhzddy'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/
  setTimeout(() => {
    patNoInput.value.focus();
    patTypeSelectRef.value?.initBaseText("门诊,急诊");
  }, 200);
  orgId = store.userInfo.orgId;

  /* 本地参数 */
  try {
    const url1 = (window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + `/api/LocalParams/get-local-setting?key=${'MZMRCXTNDSQ'}`;/* 默认打印天数 */
    const r = await LocPost(url1);
    //newForm.reqDateS
    if (!IsEmpty(r)) {
      newForm.reqDateS = formatDateTime(new Date().valueOf() - Number(r) * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');
    }
  } catch (err) { }

  try {
    const url2 = (window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + `/api/LocalParams/get-local-setting?key=${'GBMZCXHZDDYTM'}`;/* 关闭门诊查询后自动打印 */
    const rr = await LocPost(url2);
    //newForm.reqDateS
    if (!IsEmpty(rr) && (rr === '1' || rr === 1)) {
      isAutoPrint.value = '0';
    }
  } catch (err) { }

  findPatientList();
  getReportId();
});

//根据字典ID查询报表
function getReportId() {
  const url = '/api/pubReport/getReportByReportCode';
  proxy.$http
    .get(url, { params: { reportCode: '1754032534504218624' } })
    .then((res: any) => {
      reportId = res.data;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// #endregion
function setCurComputerCheckedisPrintZYD() {
  const flag = localStorage.getItem('isPrintZYD');
  if (flag) {
    localStorage.removeItem('isPrintZYD');
    isPrintZYD.value = false;
    VXETable.modal.message({ content: '取消配置成功', status: 'warning' });
  } else {
    localStorage.setItem('isPrintZYD', '1');
    isPrintZYD.value = true;
    VXETable.modal.message({ content: '配置成功', status: 'success' });
  }
}

//单元格样式
function cellStyle({ row, rowIndex, column, columnIndex }: any) {
  if (column.property === 'sameSpecCodeBgColor') {
    return { backgroundColor: row.sameSpecCodeBgColor };
  }
}

//单元格背景颜色
function cellClassName({ row, rowIndex, column, columnIndex }: any) {
  if (column.property === 'isUrgent' && row.isUrgent) {
    return 'bg-red';
  }
}

function changeDateCondition(type) {
  newForm.reqDateS = formatDateTime(
    new Date().valueOf() - 1000 * 24 * 60 * 60 * type,
    'yyyy-MM-dd 00:00:00'
  );
  newForm.reqDateE = formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59');
  findPatientList();
}

function keyupEnter(e: any) {
  if (e.$event.key == 'Enter') {
    findPrintBarcodeSpecList();
  }
}

//扫码
function EWMNoValueChangeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    const url = '/lab/hisReq/getIdCardByBarcode';
    proxy.$http
      .get(url, { params: { barcode: e.value } })
      .then((res: any) => {
        // ewmNoInput.value.focus()
        if (res.data) {
          newForm.ewmNo = res.data;
          newForm.patNo = res.data;
          findPrintBarcodeSpecList();
        }
      })
      .catch((err: any) => {
        VxeMessage('读取身份证号码失败', VxeNotifyType.error);
      });
  }
}


//身份证回车事件
function IDNoValueChangeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findPrintBarcodeSpecList();
  }
}

//读卡按钮
function IdNoFocus() {
  initWebSocket((item) => {
    console.log('item', item);
    const hasName = 'sbkh' in item.data;
    console.log(hasName); // true

    if (hasName) {
      console.log('社保卡');
      //卡号 = item.data.sbkh

      //处理卡号

      //findPrintBarcodeSpecList();
      return
    }

    if (item.code == 0) {
      newForm.IDNo = item.data.sfzh;
      findPrintBarcodeSpecList();
    } else {
      VxeMessage(item.msg, VxeNotifyType.error);
    };

    closeWebSocket();

  });
}
// 查询申请列表
function findPrintBarcodeSpecList() {
  isAutoPrint.value = getOptionValueByCodeGlobalOption('mztmdysmhzddy'); /**审核时是否弹出危急值界面 shstcwjzsbjm*/
  //判断病历号和身份证号同时为空时，不查询并进行提示
  if (IsEmpty(newForm.ewmNo)) {
    if (IsEmpty(newForm.IDNo) && IsEmpty(newForm.patNo)) {
      VxeMessage('请输入病历号或身份证号', VxeNotifyType.error);
      return;
    }
  }
  loading.value = true;
  printBarcodeList.length = 0;
  const url = '/lab/hisReq/barcodePrintSearch';
  const data = {
    patNo: newForm.patNo,
    beforePatNo: newForm.beforePatNo,
    reqNo: newForm.reqNo,
    bedNo: newForm.bedNo,
    patType: newForm.patType,
    deptNo: newForm.deptNo,
    patNa: newForm.patNa,
    IDNo: newForm.IDNo,
    reqDateS: newForm.reqDateS,
    reqDateE: newForm.reqDateE,
    searchValue: newForm.searchValue1,
    ewmNo: newForm.ewmNo,
    filterotherDept: newForm.filterotherDept
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeList.push(...res.data);
      if (printBarcodeList.length > 0) {
        let codeList = printBarcodeList.map((m: any) => m.feeCode);
        const feeCodeList = codeList.join(',');
        findFeeCodeExtenFieldsValueList(feeCodeList);
      }
      //patNoInput.value.focus();
      // proxy.$nextTick(() => {
      //     patNoInput.value.focus();
      // });
      proxy.$nextTick(() => {
        const rows = printBarcodeList.map((e) => {
          return IsEmpty(e.catchMessage) ? e : null;
        });
        printBarcodeMZTable.value?.setCheckboxRow(rows, true);
        if (rows && rows.length > 0 && (isAutoPrint.value === '1' || isAutoPrint.value === 1)) {
          console.log('自动打印');

          printManyStep1('printBarcodeMZTable');
        } else {
          loading.value = false;
        }
        patNoInput.value.focus();
      });
      //loading.value = false;
      newForm.ewmNo = '';
      selectAll();

    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}


function findFeeCodeExtenFieldsValueList(data: any) {
  console.log('data', data)
  Object.assign(newForm, {})
  const url = '/lis/fee/item/findFeeCodeExtenFieldsValueList';
  proxy.$http
    .get(url, {
      params: {
        moduleId: '1716657789982969857',
        menuId: '1734129954829893633',
        tabKey: '001',
        busRowId: data
      }
    })
    .then((res: any) => {
      if (res.data.length > 0) {
        res.data.forEach((item: any) => {
          formData[item.feeCode] = item.value;
        });
      }
      console.log('formData', formData)
    })
}

//右侧列表
function findPatientList() {
  loadingPat.value = true;
  patList.length = 0;
  const url = '/lab/hisReq/getPatInfo';
  const data = {
    patNo: newForm.patNo,
    beforePatNo: newForm.beforePatNo,
    reqNo: newForm.reqNo,
    bedNo: newForm.bedNo,
    patType: newForm.patType,
    deptNo: newForm.deptNo,
    patNa: newForm.patNa,
    IDNo: newForm.IDNo,
    reqDateS: newForm.reqDateS,
    reqDateE: newForm.reqDateE,
    searchValue: newForm.searchValue3
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      patList.push(...res.data);
      loadingPat.value = false;
    })
    .catch((err: any) => {
      loadingPat.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}
//右侧列表刷新
function RefreshPatientList() {
  clearFormConditions();
  findPatientList();
  printBarcodeList.length = 0;
}

// 右侧列表双击
function dblclickRowSelect({ row, rowIndex }) {
  newForm.beforePatNo = '';
  newForm.reqNo = '';
  newForm.patNo = row.patNo;
  newForm.patNa = row.patNa;
  newForm.IDNo = row.idNo;
  findPrintBarcodeSpecList();
}

//待打印勾选修改,为了勾选一个同医嘱的都勾选和取消
function checkboxStateChange({ checked, row }) {
  const $xTable = proxy.$refs.printBarcodeMZTable as any;
  const arr = printBarcodeList.filter((e) => {
    return e.mainId == row.mainId;
  });
  if (arr && arr.length > 0) {
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
  $xTable.updateFooter();
  proxy.$forceUpdate();
}

//待打印行点击
function printBarcodeMZRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    currentPrintBarcode = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentPrintBarcode = row;
  const xTable = proxy.$refs.printBarcodeMZTable as any;
  xTable.setCurrentRow(row);
}

//打印按钮 (准备选中的数据)
function printManyStep1(tableName: any, isAgain = false) {
  isPrintting.value = true;
  const $xTable = proxy.$refs[tableName] as any;
  if (!$xTable) {
    setTimeout(() => {
      printManyStep1(tableName, isAgain);
    }, 100);
    patNoInput.value.focus();
    loading.value = false;
    return;
  }

  const selectRows = $xTable.getCheckboxRecords();

  if (!(selectRows && selectRows.length > 0 && selectRows[0])) {
    VxeMessage('请先选中要打印的条码', VxeNotifyType.info);
    isPrintting.value = false;
  } else {
    if (isAgain) {
      printManyStep3(selectRows, isAgain);
      return;
    }
    printManyStep2(selectRows);
  }
}

// 打印
function printManyStep2(arr) {
  const data = { labHisReqList: arr };
  const url = '/lab/hisReq/barcodePrint';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      barCadeIds = res.data;
      VxeMessage(res.status.msg, VxeNotifyType.success);
      printManyStepFirst(arr);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      isPrintting.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

/**第一次打印 */
function printManyStepFirst(arr, isAgain = false) {
  if (!isAgain) {

    const maxSeq = selectAfterPrintBarcodeSpecList.length > 0
      ? Math.max(...selectAfterPrintBarcodeSpecList.map(item => item.fixedSeq))
      : 0;
    let currentSeq = maxSeq; // 临时序号变量
    arr.forEach((element) => {
      currentSeq++;
      const obj = {
        ...element,
        // uniqueId: generateUniqueId(),
        fixedSeq: currentSeq
      };
      afterPrintBarcodeSpecList.push(obj);      // const i = printBarcodeMZTable.value?.getRowIndex(element);
    });

    selectAfterPrintBarcodeSpecList = [...afterPrintBarcodeSpecList].sort(
      (a, b) => b.fixedSeq - a.fixedSeq
    );
    // 刷新表格
    const afterPrintTable = proxy.$refs.afterPrintBarcodeSpecTable as VxeTableInstance;
    afterPrintTable?.loadData(selectAfterPrintBarcodeSpecList);
    // selectAfterPrintBarcodeSpecList.unshift(...afterPrintBarcodeSpecList);
    printBarcodeMZTable.value?.removeCheckboxRow();
  }

  // 调用报表,发送打印任务
  printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: barCadeIds }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];// { id: new Date().valueOf(), params: ['123', '345', '567'] };

  //打印导引单
  if (isPrintZYD.value) {
    printParamsZydObj.value = [{ ReportName: '1768211380161925122', ReportParameters: [], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
  }

  // 清空查询条件
  clearFormConditions();
  isPrintting.value = false;
}

// 不是重打的打印之后数据放到重打列表
function printManyStep3(arr, isAgain = false) {
  //selectAfterPrintBarcodeSpecList.length = 0;
  let arrIds = [];/**重打Id 集合 */
  if (!isAgain) {
    const $xTable = proxy.$refs.printBarcodeMZTable as any;
    const indexArr = [];
    arr.forEach((element) => {
      const obj = Object.assign({}, element);
      const i = $xTable.getRowIndex(element);
      indexArr.push(i);
      afterPrintBarcodeSpecList.push(obj);
    });
    selectAfterPrintBarcodeSpecList.unshift(...afterPrintBarcodeSpecList);
    $xTable.removeCheckboxRow();
  } else {
    //重打条码
    arr.forEach(item => {
      arrIds.push(item.reqNo);
    })
  }
  let printAgainIds = arrIds ? arrIds.join(',') : '';

  // 调用报表,发送打印任务
  printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: (isAgain ? printAgainIds : barCadeIds) }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];// { id: new Date().valueOf(), params: ['123', '345', '567'] };

  //打印导引单
  if (isPrintZYD.value) {
    printParamsZydObj.value = [{ ReportName: '1768211380161925122', ReportParameters: [], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
  }

  // 清空查询条件
  clearFormConditions();
  isPrintting.value = false;
}

function clearFormConditions() {
  newForm.searchValue1 = '';
  newForm.searchValue2 = '';
  newForm.searchValue3 = '';
  newForm.patNo = '';
  newForm.beforePatNo = '';
  newForm.reqNo = '';
  newForm.bedNo = '';
  newForm.patType = [1];
  newForm.patTypeName = '门诊';
  newForm.deptNo = [];
  newForm.patNa = '';
  newForm.ewmNo = '';
  newForm.reqDateS = formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00');
  newForm.reqDateE = formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59');
  proxy.$nextTick(() => {
    patNoInput.value?.focus();  // 确保在 DOM 更新后调用
  });
}
//重打条码
function printAgain() {
  printManyStep1('afterPrintBarcodeSpecTable', true);
}

// 已打印搜索
function selectAllAfterPrintSpecs(value) {
  console.log('selectAllAfterPrintSpecs.value', value);
  if (value.$event.key !== 'Enter') {
    return;
  }
  if (IsEmpty(newForm.searchValue)) {
    selectAfterPrintBarcodeSpecList.length = 0;
    selectAfterPrintBarcodeSpecList.push(...afterPrintBarcodeSpecList);
  }
  console.log(afterPrintBarcodeSpecList, "afterPrintBarcodeSpecList");
  let arr = [];
  selectAfterPrintBarcodeSpecList.length = 0;
  //遍历afterPrintBarcodeSpecList，将搜索条件包含的数据push到selectAfterPrintBarcodeSpecList中
  for (const e of afterPrintBarcodeSpecList) {
    if (!IsEmpty(e.patNa) && e.patNa.indexOf(newForm.searchValue2) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.patNo) && e.patNo.indexOf(newForm.searchValue2) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.idNo) && e.idNo.indexOf(newForm.searchValue2) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.reqNo) && e.reqNo.includes(newForm.searchValue2)) {
      arr.push(e);
      continue;
    }
  }
  console.log('selectAllAfterPrintSpecs.arr', arr);
  if (arr.length > 0) {
    selectAfterPrintBarcodeSpecList.push(...arr);
  }
}

// 清空已打印
function deleteAllAfterPrintSpecs() {
  afterPrintBarcodeSpecList.length = 0;
  selectAfterPrintBarcodeSpecList.length = 0;
}

//已打印列表勾选状态
function afterCheckboxStateChange({ checked, row }) {
  const arr = afterPrintBarcodeSpecList.filter((e) => {
    return e.mainId == row.mainId;
  });
  if (arr && arr.length > 0) {
    const $xTable = proxy.$refs.afterPrintBarcodeSpecTable as any;
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
}

//待打印条码 合并行
let totalJe = 0;
function footerMethodTop({ columns, data }) {
  const footerData = [
    columns.map((column, _columnIndex = 12) => {
      if (_columnIndex === 12) {
        const $xTable = proxy.$refs.printBarcodeMZTable as any;
        const arr = $xTable.getCheckboxRecords();
        const sz = arr.map((p) => {
          return p.price;
        });

        totalJe = 0;

        const newsz = arr.reduce((prev, next) => {
          return prev + next.amount * next.price;
        }, 0);

        totalJe = newsz;
        return `金额合计: ${formatJe(totalJe)}  选中共计: ${arr.length} 项`;
      }
      return null;
    })
  ];

  return footerData;
}

function formatJe(v) {
  if (Number.isNaN(v)) {
    return '';
  }
  return Number(v).toFixed(2);
}

// 组件
//点击选择的那一项受检单位
function SelectRowClick(row) {
  newForm.patTypeName = row.name;
  newForm.patType = row.code;
}

// 清空表单值方法  子组件传递
function clearPatTypeName() {
  newForm.patTypeName = '';
  newForm.patType = '';
}

// 组件选中事件
function selectRow(row, index) {
  deptIds.value = '';
  newForm.deptNo.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    console.log(item);
    nameArr.push(item.name);
    newForm.deptNo.push(item.code);
    deptIdArr.push(item.id);
  });

  newForm.deptNa = nameArr.join(',');
  deptIds.value = deptIdArr.join(',');
}
// 病人来源组件选中事件
function selectPatTypeNameRow(row, index) {
  deptIds.value = '';
  newForm.patType.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.patType.push(item.code);
    deptIdArr.push(item.code);
  });

  newForm.patTypeName = nameArr.join(',');
  typeIds.value = deptIdArr.join(',');
}

function selectAll() {
  proxy.$nextTick(() => {
    // proxy.$refs.inputRef.focus();
    proxy.$refs.patNoInput.select();
  });
}
/* 已经打印条码右键点击事件 */
function contextMenuClickEvent({ menu, row, column }) {
  if (afterPrintBarcodeSpecTable.value) {
    switch (menu.code) {
      case 'copy':
        if (XEClipboard.copy(row[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' })
        }
        break
    }
  }
}
</script>

<style lang="scss" scoped>
#printBarcodeMZ {
  height: 100%;
  width: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }

    .userTable {
      height: calc(100% - 60px) !important;
    }
  }

  .printBarcodeMZTable {
    height: calc(100% - 30px) !important;
  }
}

.custom-checkbox {
  font-size: 16px;
  cursor: pointer;
}

:deep(.no-edit-close) {
  user-select: none;
  /* 禁止选择文本 */
  pointer-events: none;
  /* 禁止所有鼠标事件 */
  cursor: none;

  .vxe-form--item-content {
    opacity: 0.6;
    //增加灰度
    filter: grayscale(100%);
  }
}
</style>
